import React, { useEffect, useRef, useState } from 'react';
import classnames from 'classnames';
import styles from './SwitchTab.module.scss';

const SwitchTab = ({ tabselect, setTabselect, boxwidth, matchList, name, active }) => {
  const tabref = useRef(null);
  const tabWidth = useRef(boxwidth);
  const [transform, setTransform] = useState({});
  const tabret = useRef(null);
  const scrollContent = useRef(null);

  useEffect(() => {
    tabWidth.current = tabref.current.offsetWidth;
    scrollContent.current = tabret.current.offsetWidth;
  }, []);

  const changeTab = (e, index, item) => {
    console.log(item)
    const moveWidth = e.target.offsetLeft - (tabWidth.current - e.target.offsetWidth) / 2;
    const maxMove = scrollContent.current - tabWidth.current;
    const width = Math.max(0, Math.min(maxMove, moveWidth));
    setTransform({
      transform: `translateX(-${width}px)`,
      transition: 'all 0.3s',
    });
    setTabselect(item);
  };
  const select = (row) => {
    if (typeof active === 'string') return Reflect.get(row, active) === Reflect.get(tabselect, active)
    if (typeof active === 'function') return active(row, tabselect)
  }
  return (
    <div className={styles.Tabs} ref={tabref} style={{ width: boxwidth + 'px' }}>
      <div style={transform} ref={tabret} className={styles.scollContent}>
        {matchList?.map((item, index) => (
          <span
            onClick={(e) => {
              changeTab(e, index, item);
            }}
            key={index}
            className={classnames(
              styles.span,
              select(item) ? styles.active : null,
            )}
          >
            {Reflect.get(item, name)}
          </span>
        ))}
      </div>
    </div>
  );
};

SwitchTab.defaultProps = {
  setTabselect: () => {
    console.log('请传入对应setHook');
  },
  tabselect: 1,
  boxwidth: 358,
  name: "compName",
  active: "id"
};
export default SwitchTab;
